<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search as IconSearch, Plus as IconPlus, Delete as IconDelete, View as IconView, Edit as IconEdit } from '@element-plus/icons-vue'
// 导入分类相关的API接口
import categoryApi from '@/api/category'
import type { CategoryInfo, CreateCategoryParams, CategoryDetailResponse } from '@/api/category'

const tableData = ref<CategoryInfo[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchCategoryName = ref('')
const loading = ref(false)

// 创建分类相关的数据
const createDialogVisible = ref(false)
const createFormRef = ref()
const createForm = ref<CreateCategoryParams>({
  categoryName: '',
  description: '',
  parentId: null
})
const createFormLoading = ref(false)

// 表单验证规则
const createFormRules = {
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 删除分类相关的数据
const deleteDialogVisible = ref(false)
const deletingCategoryId = ref<number | null>(null)

// 查看分类详情相关的数据
const detailDialogVisible = ref(false)
const categoryDetail = ref<CategoryDetailResponse | null>(null)
const detailLoading = ref(false)

// 编辑分类相关的数据
const editDialogVisible = ref(false)
const editFormRef = ref()
const editForm = ref<CreateCategoryParams>({
  categoryName: '',
  description: '',
  parentId: null
})
const editingCategoryId = ref<number | null>(null)

// 获取分类列表
const getCategoryList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      categoryName: searchCategoryName.value.trim() || undefined
    }
    const res = await categoryApi.getCategoryList(params)
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getCategoryList()
}

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getCategoryList()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  getCategoryList()
}

// 处理创建分类
const handleCreate = async () => {
  if (!createFormRef.value) return
  
  await createFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await categoryApi.createCategory(createForm.value)
        ElMessage.success('创建分类成功')
        createDialogVisible.value = false
        // 重置表单
        createForm.value = {
          categoryName: '',
          description: '',
          parentId: null
        }
        // 刷新列表
        getCategoryList()
      } catch (error) {
        ElMessage.error('创建分类失败')
      }
    }
  })
}

// 取消创建
const handleCreateCancel = () => {
  createDialogVisible.value = false
  createFormRef.value?.resetFields()
}

// 处理删除按钮点击
const handleDeleteClick = (categoryId: number) => {
  deletingCategoryId.value = categoryId
  deleteDialogVisible.value = true
}

// 处理删除分类
const handleDelete = async () => {
  if (!deletingCategoryId.value) return
  
  try {
    await categoryApi.deleteCategory(deletingCategoryId.value)
    ElMessage.success('删除成功')
    deleteDialogVisible.value = false
    deletingCategoryId.value = null
    getCategoryList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 处理查看详情
const handleViewDetail = async (categoryId: number) => {
  detailLoading.value = true
  try {
    const res = await categoryApi.getCategoryById(categoryId)
    categoryDetail.value = res.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取分类详情失败')
  } finally {
    detailLoading.value = false
  }
}

// 打开编辑对话框
const handleEdit = async (categoryId: number) => {
  try {
    const res = await categoryApi.getCategoryById(categoryId)
    const data = res.data
    editForm.value = {
      categoryName: data.categoryName,
      description: data.description,
      parentId: data.parentId
    }
    editingCategoryId.value = categoryId
    editDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取分类信息失败')
  }
}

onMounted(() => {
  getCategoryList()
})
</script>

<template>
  <div class="category-list-container">
    <div class="search-bar">
      <el-button type="primary" :icon="IconPlus" @click="createDialogVisible = true">新增分类</el-button>
      <el-input
        v-model="searchCategoryName"
        placeholder="请输入分类名称"
        class="search-input"
        :prefix-icon="IconSearch"
        @keyup.enter="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>

    <el-table
      :data="tableData"
      row-key="categoryId"
      border
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      v-loading="loading"
      class="category-table"
    >
      <el-table-column prop="categoryId" label="分类ID" width="100" />
      <el-table-column prop="categoryName" label="分类名称" width="180" />
      <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="parentId" label="父级ID" width="100">
        <template #default="{ row }">
          {{ row.parentId || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column prop="updatedAt" label="更新时间" width="180" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <div class="action-btns">
            <el-button
              type="primary"
              :icon="IconView"
              circle
              @click="handleViewDetail(row.categoryId)"
            />
            <el-button
              type="warning"
              :icon="IconEdit"
              circle
              @click="handleEdit(row.categoryId)"
            />
            <el-button
              type="danger"
              :icon="IconDelete"
              circle
              @click="handleDeleteClick(row.categoryId)"
            />
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :disabled="!total"
      />
    </div>
  </div>

  <!-- 创建分类对话框 -->
  <el-dialog
    v-model="createDialogVisible"
    title="创建分类"
    width="500px"
    @close="handleCreateCancel"
  >
    <el-form
      ref="createFormRef"
      :model="createForm"
      :rules="createFormRules"
      label-width="100px"
    >
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="createForm.categoryName" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="createForm.description"
          type="textarea"
          :rows="3"
          placeholder="请输入描述信息"
        />
      </el-form-item>
      <el-form-item label="父级分类" prop="parentId">
        <el-cascader
          v-model="createForm.parentId"
          :options="tableData"
          :props="{
            checkStrictly: true,
            label: 'categoryName',
            value: 'categoryId',
            emitPath: false
          }"
          placeholder="请选择父级分类"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button link @click="handleCreateCancel">取消</el-button>
        <el-button type="primary" @click="handleCreate">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 删除确认对话框 -->
  <el-dialog
    v-model="deleteDialogVisible"
    title="删除确认"
    width="400px"
  >
    <p>确定要删除该分类吗？此操作不可恢复。</p>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleDelete">确定删除</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 分类详情对话框 -->
  <el-dialog
    v-model="detailDialogVisible"
    title="分类详情"
    width="600px"
  >
    <div v-loading="detailLoading">
      <template v-if="categoryDetail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="分类ID">
            {{ categoryDetail.categoryId }}
          </el-descriptions-item>
          <el-descriptions-item label="分类名称">
            {{ categoryDetail.categoryName }}
          </el-descriptions-item>
          <el-descriptions-item label="描述">
            {{ categoryDetail.description || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="父级ID">
            {{ categoryDetail.parentId || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ categoryDetail.createdAt }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ categoryDetail.updatedAt }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="sub-categories" v-if="categoryDetail.children?.length">
          <h3>子分类列表</h3>
          <el-table :data="categoryDetail.children" border>
            <el-table-column prop="categoryId" label="分类ID" width="100" />
            <el-table-column prop="categoryName" label="分类名称" width="180" />
            <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
          </el-table>
        </div>
      </template>
    </div>
  </el-dialog>

  <!-- 编辑分类对话框（基础结构） -->
  <el-dialog
    v-model="editDialogVisible"
    title="编辑分类"
    width="500px"
  >
    <el-form
      ref="editFormRef"
      :model="editForm"
      :rules="createFormRules"
      label-width="100px"
    >
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="editForm.categoryName" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="editForm.description"
          type="textarea"
          :rows="3"
          placeholder="请输入描述信息"
        />
      </el-form-item>
      <el-form-item label="父级分类" prop="parentId">
        <el-cascader
          v-model="editForm.parentId"
          :options="tableData"
          :props="{
            checkStrictly: true,
            label: 'categoryName',
            value: 'categoryId',
            emitPath: false
          }"
          placeholder="请选择父级分类"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.category-list-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  justify-content: space-between;
}

.search-bar :deep(.el-input) {
  margin-left: auto;
}

.search-inputs {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

.search-input {
  width: 200px;
}

.category-table {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-cascader {
  width: 100%;
}

.sub-categories {
  margin-top: 20px;
}

.sub-categories h3 {
  margin-bottom: 15px;
  font-size: 16px;
  color: #606266;
}

.action-btns {
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-button + .el-button {
  margin-left: 8px;
}

.el-button.is-circle {
  padding: 6px;
}
</style>